﻿using System.Web;
using System.Web.Mvc;
using BSF.Db;
using BSF.Extensions;
using BSF.ServicesResult;
using BSF.Tool;

namespace HuntingFishGame.OpenApi
{
    public class CrossDoMainAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 这种方法称为后执行的控制器操作结果
        /// </summary>
        /// <param name="filterContext">提供 ActionFilterAttribute 类的 OnResultExecuted 方法的上下文</param>
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            string jsons = GetJson(filterContext);
            if(string.IsNullOrWhiteSpace(jsons))
                return;
            var _req = CommonHelper.GetRequest();//获取请求
            #region 跨域请求返回(增加模块)
            int crossdomain = LibConvert.ObjToInt(RequestMethodHelper.RequestParamValue(_req, "crossdomain"));
            if (crossdomain == 1)
            {
                //string jsons = Newtonsoft.Json.JsonConvert.SerializeObject(r1.data);
                var response = HttpContext.Current.Response;
                response.ContentType = "text/html";
                response.Charset = "utf-8"; //设置输出流的字符集-中文
                response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); //设置输出流的字符集
                //获取回调函数名
                var context = System.Web.HttpContext.Current.Request;
                string callback = context.QueryString["success_jsonpCallback"];
                response.Write(callback + "(" + jsons + ")");
                response.End();
            }

            #endregion
        }


        private string GetJson(ResultExecutedContext filterContext)
        {
            string jsons = string.Empty;
            var r = filterContext.Result;
            if (r.GetType() == typeof(ApiResult<>)) //如果是列表类型的，需要记录总记录数和列表集合
            {
                dynamic r1 = r;
                jsons = Newtonsoft.Json.JsonConvert.SerializeObject(r1.data);
            }
            else if (r.GetType() == typeof(ApiResult))
            {
                dynamic r1 = r;
                jsons = Newtonsoft.Json.JsonConvert.SerializeObject(r1.data);
            }
            return jsons;
        }
    }
}